package com.example.farmer.Activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.farmer.Database.CartDatabase;
import com.example.farmer.Database.ProductPublishDatabase;
import com.example.farmer.Entity.CartItem;
import com.example.farmer.Entity.Order;
import com.example.farmer.Entity.ProductPost;
import com.example.farmer.R;
import com.example.farmer.wode.CarActivity;
import com.example.farmer.wode.ConfirmOrderActivity;

public class ProductDetail extends AppCompatActivity {
    private static final String PRODUCT_ID = "PRODUCT_ID";
    private ProductPublishDatabase db;
    private int productId;
    private ImageView product_image;
    private ImageButton back_button,shopping_cart,dianpu,kefu,dianhua;
    private TextView price,product_title,shipaddress,freight,usernumber,jindianpu,add_shopping_cart,buy_now;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_activity);

        // 初始化数据库帮助类
        db = ProductPublishDatabase.getInstance(this);

        // 从Intent获取商品ID
        productId = getIntent().getIntExtra("PRODUCT_ID", -1);

        // 根据商品ID加载商品详情
        if (productId != -1) {
            loadProductDetail();
        }
    }

    private void loadProductDetail() {


//        SharedPreferences sharedPreferences = getSharedPreferences("loginNumber", Context.MODE_PRIVATE);
//        String userNumber = sharedPreferences.getString("userNumber" , "") ;
        // 隐藏手机号中间四位

        ProductPost productPost = db.getProductPostById(productId);
        if (productPost != null) {
            // 绑定商品详情到界面元素
            // 显示商品详情，包括客服电话
            String customerServicePhone = productPost.getUserNumber();
            // 可以将客服电话设置到界面上的某个 TextView 或保存以供后续使用

            back_button = findViewById(R.id.back_button);
            back_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();//结束活动返回
                }
            });

            shopping_cart = findViewById(R.id.shopping_cart);
            shopping_cart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 点击购物车按钮时的操作
                    Intent intent = new Intent(ProductDetail.this, CarActivity.class);
                    startActivity(intent);
                }
            });

            dianpu = findViewById(R.id.dianpu);
            kefu = findViewById(R.id.kefu);
            kefu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 跳转到客服聊天页面
                    Intent customerIntent = new Intent(ProductDetail.this, CustomerServiceActivity.class);
                    customerIntent.putExtra(PRODUCT_ID, productId);
                    customerIntent.putExtra("CUSTOMER_SERVICE_PHONE", customerServicePhone);
                    startActivity(customerIntent);
                }
            });

            //设置电话按钮事件
            dianhua = findViewById(R.id.dianhua);
            dianhua.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String phoneNumber = "tel:" + customerServicePhone;
                    Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(phoneNumber));
                    startActivity(callIntent);
                }
            });

            add_shopping_cart = findViewById(R.id.add_shopping_cart);
            //设置加入购物车按钮事件
            add_shopping_cart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    // 假设productPost是当前商品的信息
                    showCartDialog(productPost);
                }
            });


            buy_now = findViewById(R.id.buy_now);
            //设置立即购买按钮事件
            buy_now.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    showBuyDialog(productPost);
                    Intent intent = new Intent(ProductDetail.this,ConfirmOrderActivity.class);
                    intent.putExtra(PRODUCT_ID, productId);
                    startActivity(intent);
                }
            });


            jindianpu = findViewById(R.id.jindianpu);


            product_image = findViewById(R.id.product_image);
            price = findViewById(R.id.price);
            product_title = findViewById(R.id.product_title);
            shipaddress = findViewById(R.id.shipaddress);
            freight = findViewById(R.id.freight);
            usernumber = findViewById(R.id.usernumber);


            // 假设您已经配置了Glide用于图片加载
            Glide.with(this)
                    .load(productPost.getImageUri())
                    .into(product_image);

            price.setText(String.valueOf(productPost.getPrices()));
            product_title.setText(productPost.getTitle());
            shipaddress.setText(productPost.getShipaddress());
            freight.setText(String.valueOf(productPost.getFreight()));
            usernumber.setText(hideMiddleFourDigits(productPost.getUserNumber()));

        }

    }

    // 隐藏中间四位数字的方法
    private String hideMiddleFourDigits(String number) {
        if (number == null || number.length() < 8) {
            // 如果手机号长度不足8位，直接返回原手机号或提示信息
            return "Invalid number";
        }
        // 取手机号的前三位和后四位，中间用星号替换
        return number.substring(0, 3) + "****" + number.substring(number.length() - 4);
    }

    //购物车
    @SuppressLint("SetTextI18n")
    private void showCartDialog(ProductPost productPost) {
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.cart_dialog);

        ImageView productImageDialog = dialog.findViewById(R.id.product_image_dialog);
        TextView productPriceDialog = dialog.findViewById(R.id.product_price_dialog);
        TextView totalPriceDialog = dialog.findViewById(R.id.total_price_dialog);
        Button addToCartButton = dialog.findViewById(R.id.add_to_cart_button);
        ImageButton quantityDecreaseButton = dialog.findViewById(R.id.quantity_decrease_button);
        ImageButton quantityIncreaseButton = dialog.findViewById(R.id.quantity_increase_button);
        TextView quantityValueDialog = dialog.findViewById(R.id.quantity_value_dialog);

        // 假设您已经配置了Glide用于图片加载
        Glide.with(this)
                .load(productPost.getImageUri())
                .into(productImageDialog);

        productPriceDialog.setText("¥" + productPost.getPrices());
        totalPriceDialog.setText("合计：¥" + productPost.getPrices());

        final int[] quantity = {1}; // 默认购买数量
        quantityValueDialog.setText(String.valueOf(quantity[0]));

        quantityDecreaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                quantity[0] = Math.max(1, quantity[0] - 1); // 至少为1
                quantityValueDialog.setText(String.valueOf(quantity[0]));
                updateTotalPrice(totalPriceDialog, productPost.getPrices(), quantity[0]);
            }
        });

        quantityIncreaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                quantity[0]++;
                quantityValueDialog.setText(String.valueOf(quantity[0]));
                updateTotalPrice(totalPriceDialog, productPost.getPrices(), quantity[0]);
            }
        });

        addToCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 创建一个新的CartItem实例
                CartItem cartItem = new CartItem(
                        /* id */ 0, // 通常由数据库自动生成
                        productPost.getId(), // 假设ProductPost类有getId()方法
                        productPost.getTitle(), // 假设ProductPost类有getTitle()方法
                        productPost.getPrices(),
                        Integer.parseInt(quantityValueDialog.getText().toString()),
                        productPost.getImageUri()
                );

                // 获取数据库帮助类实例
                CartDatabase dbHelper = new CartDatabase(ProductDetail.this);

                // 将CartItem添加到数据库
                dbHelper.addCartItem(cartItem);

                dialog.dismiss();
                Toast.makeText(ProductDetail.this, "商品已添加到购物车", Toast.LENGTH_SHORT).show();
            }
        });

        dialog.show();
    }


//    //立即购买
//    @SuppressLint("SetTextI18n")
//    private void showBuyDialog(ProductPost productPost) {
//        final Dialog dialog = new Dialog(this);
//        dialog.setContentView(R.layout.cart_buy_dialog);
//
//        ImageView productImageDialog = dialog.findViewById(R.id.product_image_dialog);
//        TextView productPriceDialog = dialog.findViewById(R.id.product_price_dialog);
//        TextView totalPriceDialog = dialog.findViewById(R.id.total_price_dialog);
//        Button addToBuyButton = dialog.findViewById(R.id.add_to_buy_button);
//        ImageButton quantityDecreaseButton = dialog.findViewById(R.id.quantity_decrease_button);
//        ImageButton quantityIncreaseButton = dialog.findViewById(R.id.quantity_increase_button);
//        TextView quantityValueDialog = dialog.findViewById(R.id.quantity_value_dialog);
//
//        // 假设您已经配置了Glide用于图片加载
//        Glide.with(this)
//                .load(productPost.getImageUri())
//                .into(productImageDialog);
//
//        productPriceDialog.setText("¥" + productPost.getPrices());
//        totalPriceDialog.setText("合计：¥" + productPost.getPrices());
//
//        final int[] quantity = {1}; // 默认购买数量
//        quantityValueDialog.setText(String.valueOf(quantity[0]));
//
//        quantityDecreaseButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                quantity[0] = Math.max(1, quantity[0] - 1); // 至少为1
//                quantityValueDialog.setText(String.valueOf(quantity[0]));
//                updateTotalPrice(totalPriceDialog, productPost.getPrices(), quantity[0]);
//            }
//        });
//
//        quantityIncreaseButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                quantity[0]++;
//                quantityValueDialog.setText(String.valueOf(quantity[0]));
//                updateTotalPrice(totalPriceDialog, productPost.getPrices(), quantity[0]);
//            }
//        });
//
//        addToBuyButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                // 获取商品信息
//                String productName = productPost.getTitle();
//                String productImage = productPost.getImageUri(); // 假设 imageUri 是图片的 URI 字符串
//                int[] quantity = new int[]{Integer.parseInt(quantityValueDialog.getText().toString())};
//                double productPrice = productPost.getPrices();
//
//                // 创建Intent，准备跳转到确认订单页面
//                Intent intent = new Intent(ProductDetail.this, ConfirmOrderActivity.class);
//                intent.putExtra("PRODUCT_NAME", productName);
//                intent.putExtra("PRODUCT_IMAGE", productImage);
//                intent.putExtra("QUANTITY", quantity);
//                intent.putExtra("PRODUCT_PRICE", productPrice);
//
//                // 启动ConfirmOrderActivity
//                startActivity(intent);
//            }
//        });
//
//        dialog.show();
//    }

    private void updateTotalPrice(TextView totalPriceTextView, double price, int quantity) {
        double totalPrice = price * quantity;
        totalPriceTextView.setText("合计：¥" + String.format("%.2f", totalPrice));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (db != null) {
            db.close(); // 关闭数据库
        }
    }
}
